package 查找算法;

public class Test {
    public static void main(String[] args) {
        int[] arr = {7, 23, 79, 81, 103, 127, 131, 147};
        // 前提条件: 数组中的数据必须是有序的
        // 核心思想: 每次排除一半的数据, 查询数据的性能明显提高极多.
        System.out.println(binarySearch(arr,8));
    }
    public static int binarySearch(int[] arr, int date) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int middle = (left + right) / 2;
            if (date < arr[middle]) {
                right = middle - 1;
            } else if (date > arr[middle]) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}


